package com.suyang.syt.controller;

import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.suyang.syt.model.WeixinMsgReceive;
import com.suyang.syt.service.interfaces.WeixinMsgReceiveService;
import com.suyang.syt.service.interfaces.WeixinMsgReplyService;
import com.suyang.syt.util.DateFormat;
import com.suyang.syt.util.EmptyUtil;
import com.suyang.syt.util.Sha1Util;
import com.suyang.syt.weixin.WeixinKit;

@Controller
@RequestMapping("/weixin")
public class WeixinIndexController {
	public static final String TOKEN = "tongqutang";

	@Autowired
	private WeixinMsgReceiveService weixinMsgReceiveService;
	@Autowired
	private WeixinMsgReplyService weixinReplyMsgService;

	@RequestMapping(value = "/get", method = RequestMethod.GET)
	public void get(HttpServletRequest request, HttpServletResponse response) {
		try {
			String signature = request.getParameter("signature");
			String timestamp = request.getParameter("timestamp");
			String nonce = request.getParameter("nonce");
			String echostr = request.getParameter("echostr");
			if (EmptyUtil.isEmpty(signature) || EmptyUtil.isEmpty(timestamp) || EmptyUtil.isEmpty(nonce) || EmptyUtil.isEmpty(echostr)) {
				return;
			}
			String[] arr = { TOKEN, timestamp, nonce };
			Arrays.sort(arr);
			StringBuilder sb = new StringBuilder();
			for (String s : arr) {
				sb.append(s);
			}
			if (signature.equals(Sha1Util.sha1(sb.toString()))) {
				PrintWriter printWriter = response.getWriter();
				printWriter.println(echostr);
				printWriter.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/get", method = RequestMethod.POST)
	public void getInfo(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 1.读取xml字符串,解析xml,将消息存入数据库
			WeixinMsgReceive weixinMsgReceive = WeixinKit.doParseXML(request.getInputStream());
			// 2.判断消息类型,生成回复消息内容,xml格式的字符串
			weixinMsgReceiveService.add(weixinMsgReceive);
			// 3.将返回的内容通过微信平台发送给用户
			String content = weixinReplyMsgService.addReplyMsg(weixinMsgReceive);
			if (EmptyUtil.isNotEmpty(content)) {
				System.out.println(DateFormat.dateToString(new Date()) + "---->发送了请求:" + content);
				response.setContentType("application/xml;charset=UTF-8");
				response.setCharacterEncoding("UTF-8");
				PrintWriter printWriter = response.getWriter();
				printWriter.println(content);
				printWriter.flush();
				printWriter.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
